package com.red.controller;

import com.red.pojo.Page;
import com.red.pojo.Result;
import com.red.pojo.entity.House;
import com.red.pojo.model.LoginUser;
import com.red.service.IHouseService;
import com.red.util.HttpStatusUtil;
import com.red.util.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/house")
public class HouseController {

    @Autowired
    private IHouseService houseService;

    @PostMapping
    public Result add(House house, HttpServletRequest request) {
        LoginUser loginUser = JWTUtil.getLoginUser(request);

        String msg;

        // loginUser可能为空，但token拦截器已经对这种情况做了堵截
        if (loginUser == null) {
            msg = "不可能发生的登录用户信息为空";
        } else if (house.getPrice() <= 0) {
            msg = "价格不能小于或等于0";
        } else if (house.getAddress() == null || house.getAddress().isEmpty()) {
            msg = "地址不能为空";
        } else if (house.getHouseName() == null || house.getHouseName().isEmpty()) {
            msg = "房源名不能为空";
        } else if (house.getDetailedAddress() == null || house.getDetailedAddress().isEmpty()) {
            msg = "详细地址不能为空";
        } else {
            house.setUserId(loginUser.getUserID());
            return houseService.insertHouse(house) > 0 ? Result.success() : Result.error("核验通过，但插入时失败");
        }

        return Result.error(msg);
    }

    @DeleteMapping
    public Result delete(@RequestParam int houseId) {
        return houseService.deleteHouseByID(houseId) > 0 ? Result.success() : Result.error();
    }

    @PutMapping
    public Result update(House house) {
        if (house.getHouseId() <= 0) {
            return Result.error("需要正确的参数");
        }

        return houseService.updateHouse(house) > 0 ? Result.success() : Result.error();
    }

    @GetMapping("/{page}/{size}")
    public Result list(House house, @PathVariable int page, @PathVariable int size) {
        ArrayList<Object> payload = new ArrayList<>();
        Page page1 = new Page(houseService.selectHouseCount(house), page, size);
        List<House> houses = houseService.selectHouseList(house, page1.getCurrent(), page1.getSize());

        payload.add(houses);
        payload.add(page1);

        return new Result(HttpStatusUtil.SUCCESS, "获取成功", payload);
    }

    @GetMapping("/public/detail/{houseId}")
    public Result houseDetail(@PathVariable int houseId) {
        House house = houseService.selectHouseByID(houseId);

        if (house != null) {
            return new Result(HttpStatusUtil.SUCCESS, "获取成功", house);
        } else {
            return Result.error("houseId不存在");
        }
    }
}
